import http.client
import urllib.parse

class ApiClient:
    url = ''
    error = ''
    headers = {}

    def __init__(self, url):
        self.url = url.strip()

    def conn(self):

        conn = None
        if self.url:
            if self.url[0:5] == 'https':

                conn = http.client.HTTPSConnection(self.url, 80)
            else:
                conn = http.client.HTTPConnection(self.url, 80)

        return conn

    def get(self, path='/', body=None, headers=None):
        if not headers:
            headers = {}

        request_headers = self.headers.copy()
        request_headers.update(headers)

        conn = self.conn()
        if body:
            if not isinstance(body, str):
                body = urllib.parse.urlencode(body)
            path += '?' + body

        conn.request("GET", path, headers=request_headers)

        re = conn.getresponse()

        data = None
        if re.status == 200:
            data = re.read()
        else:
            self.error = re.reason
        conn.close()

        return data

    def post(self, path='/', body=None, headers=None):
        if not headers:
            headers = {}
        request_headers = self.headers.copy()
        request_headers.update(headers)

        if body:
            body = urllib.parse.urlencode(body)

        conn = self.conn()
        conn.request("POST", path, body=body, headers=request_headers)
        re = conn.getresponse()

        data = None
        if re.status == 200:
            data = re.read()
        else:
            self.error = re.reason
        conn.close()

        return data


class ApiClientError(Exception):

    def __init__(self, msg):
        super(self.__class__, self).__init__(self, msg)